<?php

namespace mpend\modules\passport\models;

use Yii;
use yii\db\Exception;
use common\base\Model;
use common\logics\SmsCaptchaForm;
use mpend\models\User;
use common\models\user\UserMeta;
use common\models\user\UserConnect;

/**
 * 绑定手机号模型
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class BindMobileForm extends Model {

    /**
     * @var string 待绑定的手机号
     */
    public $mobile;

    /**
     * @var string 待校验的验证码
     */
    public $code;

    /**
     * @var string 第三方连接ID
     */
    public $connect_id = null;

    /**
     * @var string 待校验的验证码
     */
    public $token;

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['mobile', 'code'], 'required'],
            ['mobile', 'string', 'min' => 11, 'max' => 11],
            ['code', 'string', 'min' => 6, 'max' => 6],
            ['mobile', '\common\validators\MobileValidator'],
            ['mobile', 'validateUser'],
            ['code', 'validateCaptcha'],
            ['connect_id', 'safe'],
            ['token', 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
            'mobile' => '手机号',
            'code' => '短信验证码',
        ];
    }

    /**
     * Validates the password.
     * This method serves as the inline validation for password.
     *
     * @param string $attribute the attribute currently being validated
     * @param array $params the additional name-value pairs given in the rule
     */
    public function validateUser($attribute) {
        if ($this->hasErrors()) {
            return;
        }
        $user = User::findByMobile($this->$attribute);
        if ($user) {
            $this->addError($attribute, '该手机号已被其他用户绑定，不能重复绑定!');
        }
    }

    /**
     * Validates the password.
     * This method serves as the inline validation for password.
     *
     * @param string $attribute the attribute currently being validated
     * @param array $params the additional name-value pairs given in the rule
     */
    public function validateCaptcha($attribute) {
        if ($this->hasErrors()) {
            return;
        }
        $cache = $this->getCommonCache();
        $captcha = $cache->get('captcha_' . SmsCaptchaForm::SCOPE_BIND . '_' . $this->mobile);
        if ($captcha == false || $captcha !== $this->$attribute) {
            if ($captcha == false) {
                Yii::error([
                    'message' => $this->getAttributeLabel($attribute) . '已过期',
                    $attribute => $this->$attribute,
                    'cache' => $captcha,
                ]);
            } elseif ($captcha !== $this->$attribute) {
                Yii::error([
                    'message' => $this->getAttributeLabel($attribute) . '不正确',
                    $attribute => $this->$attribute,
                    'cache' => $captcha,
                ]);
            }
            return $this->addError($attribute, $this->getAttributeLabel($attribute) . '不正确或者已过期');
        }
    }

    /**
     * @return \common\models\user\UserMeta|null
     */
    protected function getUser() {
        if ($this->token) {
            return User::findOne($this->token->user_id);
        }
        return null;
    }

    /**
     * @return \common\models\user\UserMeta|null
     */
    protected function getConnect() {
        if ($this->connect_id) {
            return UserConnect::findOne($this->connect_id);
        }
        return null;
    }

    /**
     * Sends an email to the specified email address using the information collected by this model.
     *
     * @param string $email the target email address
     * @return bool whether the email was sent
     */
    public function bind() {
        if (!$this->validate()) {
            $this->dumpError();
        }
        $connect = $this->getConnect();
        if ($connect) {
            $meta = $connect->autoRegister($this->mobile);
            if ($meta == false) {
                $this->dumpError('自动注册失败');
            }
            $token = $this->token;
            if (!$token->bindUser($meta->id)) {
                $this->dumpError('授权信息Token绑定失败');
            }
            return $meta;
        }
        $user = $this->executeTransaction(__FUNCTION__);
        $cache = $this->getCommonCache();
        $cache->delete('captcha_' . SmsCaptchaForm::SCOPE_BIND . '_' . $this->mobile);
        return $user;
    }

    /**
     * 数据保存
     * @inheritdoc
     */
    protected function transactBind() {
        $user = $this->getUser();
        if (!$user) {
            $this->dumpError('当前没登陆任何用户');
        }
        $user->setMobile($this->mobile);
        if (!$user->save()) {
            throw new Exception($user->getErrorMsg());
        }
        return $user;
    }

}
